import { ApiUrl } from '../service/env.js';
import { getDistrictSync, getEastPayDistrictSync } from '@/service/common/city.service.js';
import { getWxConfigInfoApi } from '@/service/common/common.service.js';

const isInWXWebview = () => { // 判断是否是微信公众号环境
  return window && window.navigator.userAgent.indexOf('MicroMessenger') > 0;
};

const decideEnv = () => { // 判断当前环境是微信还是支付宝
  let applyType;
  if (window && window.navigator.userAgent.indexOf('MicroMessenger') > 0) {
    applyType = 'wx';
  } else if (window && window.navigator.userAgent.indexOf('AlipayClient') > 0) {
    applyType = 'zfb';
  }
  return applyType;
};

const isIOS = () => {
  let u = navigator.userAgent;
  let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  return isiOS;
};

const uploadFile = opt => { // 上传图片
  opt = opt || {};
  opt.url = opt.url || '/file/upload';
  opt.name = opt.name || 'file'; // 文件对应的key,开发者在服务器端通过这个key可以获取到文件二进制内容
  opt.success = opt.success || function () {};
  let token = '';
  uni.getStorage({
    key: 'user_token',
    success: function (res) {
      token = res.data;
      if (!token) {
        uni.showToast({
          title: '请先登录！',
          icon: 'none',
          success: () => {
            
          }
        });
        // return false;
      } else {
        uni.chooseImage({
          count: 1,
          sizeType: ['original'],
          success (res) {
            // 因为有一张图片，输出下标[0]，直接输出地址
            let imgFiles = res.tempFilePaths[0];
            // 上传图片
            // 做成一个上传对象
            uni.showLoading({
              title: '上传中...',
              mask: true
            });
            uni.uploadFile({
              url: ApiUrl + opt.url + '?token=' + token,
              filePath: imgFiles,
              name: opt.name,
              dataType: 'json',
              success: function (res) {
                opt.success(JSON.parse(res.data));
                uni.hideLoading();
              },
              fail: function () {
                uni.hideLoading();
                uni.showToast({
                  title: '请稍后重试',
                  icon: 'none'
                });
              },
              complete: function () {
                //
              }
            });
          },
          fail: () => {
            // console.log('fail');
          },
          complete: () => {
            // console.log('complete');
          }
        });
      }
    },
    fail: function (res) {
      uni.showToast({
        title: '请先登录！',
        icon: 'none',
        success: () => {
          
        }
      });
      return false;
    }
  });
};

const getUrlParam = (name) => { // 截取url参数
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); // 构造一个含有目标参数的正则表达式对象
  let r = window.location.search.substr(1).match(reg); // 匹配目标参数
  if (r != null) {
    return decodeURI(r[2]);
  }
  return null; // 返回参数值
};

const processParams = (obj) => { // 去除空的参数
  let param = {};
  if (obj === null || obj === undefined || obj === '') return param;
  for (var key in obj) {
    if (obj[key] !== null && obj[key] !== undefined && obj[key] !== '') {
      param[key] = typeof obj[key] === 'string' ? trim(obj[key]) : obj[key];
    }
  }
  return param;
};

const initMultDistrictArray = async opt => { // 初始化城市数据 opt: type : 1 或者未传参 为正常地址选择 2：易生支付地址
  let multiDistrictArray = [];
  let multiDistrictIndex = [];
  let multiDistrictIds = [];
  if (opt.district && opt.district.length > 0) {
    opt.type === 2 ? multiDistrictArray.push(await getEastPayDistrictSync({ parentId: null, type: 0 })) : multiDistrictArray.push(await getDistrictSync({ parentId: null, type: 0 })); // 首列收据
    for (let i = 0; i < opt.district.length - 1; i++) {
      multiDistrictArray.push(opt.type === 2 ? await getEastPayDistrictSync({ parentId: opt.district[i], type: i + 1 }) : await getDistrictSync({ parentId: opt.district[i], type: i + 1 }));
    }
    opt.district.forEach((districtItem, districtIndex) => {
      multiDistrictArray[districtIndex].forEach((item, index) => {
        if (districtItem === item.id) {
          multiDistrictIndex.push(index);
          multiDistrictIds.push(item.id);
        }
      });
    });
  } else {
    let length = opt.length || 3;
    for (let i = 0; i < length; i++) {
      if (i === 0) {
        multiDistrictArray.push(opt.type === 2 ? await getEastPayDistrictSync({ parentId: null, type: i }) : await getDistrictSync({ parentId: null, type: i }));
      } else {
        multiDistrictArray.push(opt.type === 2 ? await getEastPayDistrictSync({ parentId: multiDistrictArray[i - 1][0].id, type: i }) : await getDistrictSync({ parentId: multiDistrictArray[i - 1][0].id, type: i }));
      }
      multiDistrictIds.push(multiDistrictArray[i][0].id);
      multiDistrictIndex.push(0);
    }
  }
  return {
    multiDistrictArray: multiDistrictArray,
    multiDistrictIndex: multiDistrictIndex,
    multiDistrictIds: multiDistrictIds
  };
};

const bindDistrictColumnPickerChange = async (opt) => { // 城市选择列发生变化 opt: type : 1 或者未传参 为正常地址选择 2：易生支付地址
  let multiDistrictIds = [];
  for (let i = opt.column; i < opt.multiDistrictArray.length - 1; i++) {
    if (i === opt.column) {
      opt.multiDistrictArray[i + 1] = opt.type === 2 ? await getEastPayDistrictSync({ parentId: opt.multiDistrictArray[opt.column][opt.index].id, type: opt.column + 1 }) : await getDistrictSync({ parentId: opt.multiDistrictArray[opt.column][opt.index].id, type: opt.column + 1 });
    } else if (opt.multiDistrictArray[i].length > 0) {
      opt.multiDistrictArray[i + 1] = opt.type === 2 ? await getEastPayDistrictSync({ parentId: opt.multiDistrictArray[i][0].id }) : await getDistrictSync({ parentId: opt.multiDistrictArray[i][0].id });
      opt.multiDistrictIndex[i] = 0;
    } else {
      opt.multiDistrictArray[i + 1] = [];
      opt.multiDistrictIndex[i] = 0;
    }
  }
  opt.multiDistrictIndex[opt.multiDistrictArray.length - 1] = 0;
  opt.multiDistrictIndex[opt.column] = opt.index;
  opt.multiDistrictIndex.forEach((districtItem, districtIndex) => {
    opt.multiDistrictArray[districtIndex].forEach((item, index) => {
      if (districtItem === index) {
        multiDistrictIds.push(item.id);
      }
    });
  });
  return {
    multiDistrictArray: opt.multiDistrictArray,
    multiDistrictIndex: opt.multiDistrictIndex,
    multiDistrictIds: multiDistrictIds
  };
};

const multiDistrict = { // 城市选择相关方法
  initMultDistrictArray: initMultDistrictArray,
  bindDistrictColumnPickerChange: bindDistrictColumnPickerChange
};

const setWxConfigSync = () => { // 设置微信config
  var jswx = require('jweixin-module'); // npm安装的引用
  let surl = window.location.href.split('#')[0];
  // if (isIOS()) {
  //   surl = window.initUrl;
  // } else {
  //   surl = window.location.href.split('#')[0];
  // }
  /* eslint-disable */
  return new Promise((resolve, reject) => {
    getWxConfigInfoApi({ url: surl }, res => {
        if (res.status === 0) {
          jswx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: res.data.appId, // 必填，公众号的唯一标识
            timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
            signature: res.data.signature, // 必填,签名,见附录1
            // surl: surl, // 自己添加的，debug为true的时候可以网页打印出对应的URL是否正确
            jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode', 'getLocation']
          });
          jswx.ready(function () {
            resolve(jswx);
          });
        }
      });
  });
  /* eslint-disable */
};

const setWxConfig = () => { // 设置微信config
  var jswx = require('jweixin-module'); // npm安装的引用
  let surl = window.location.href.split('#')[0]; // 据说可以解决URL中带参数的问题;
  /* eslint-disable */
  getWxConfigInfoApi({ url: surl }, res => {
      if (res.status === 0) {
        jswx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: res.data.appId, // 必填，公众号的唯一标识
          timestamp: res.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.data.nonceStr, // 必填,生成签名的随机串
          signature: res.data.signature, // 必填,签名,见附录1
          // surl: surl, // 自己添加的，debug为true的时候可以网页打印出对应的URL是否正确
          jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode', 'getLocation']
        });
      }
    });
    return jswx;
  /* eslint-disable */
};

const trim = (str) => { // 去除字符串前后所有空
  return str.replace(/(^\s*)|(\s*$)/g, ""); 
}

// 预览图片
const checkImage = (imgList, index) => {
  // imgList: 预览图片的数组  index: 当前图片的索引
  uni.previewImage({
    urls: imgList,
    current : index || 0, // 根据索引打开当前的图片
    longPressActions: {
      success: function(data) {
        console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
      },
      fail: function(err) {
        console.log(err.errMsg);
      }
    }
  });
}

const exportFile = function (blobData, filename, type, suffix) { // 导出文件 1、filename: 导出的文件名称 2、type: 文件类型 默认类型 ''application/vnd.ms-excel'参考：https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types/ 3、suffix: 导出文件后缀名，默认值.xls .zip, .png, .xls之类的
  let fileName = new Date().getTime() + filename + (suffix || '.xlsx');
  let blob = new Blob([blobData], {type: type || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
  if (window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(blob, fileName);
  } else {
    let downloadElement = document.createElement('a');
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    console.log(href,'href')
    downloadElement.href = href;
    downloadElement.download = fileName; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  }
}

const watchPrePage = () => {
  var pages = getCurrentPages();
  var currPage = pages[pages.length - 1]; //返回后的页面
  // var prevPage = pages[pages.length - 2]; //上一个页面
  currPage.$vm.currentPageIsUpload = true;
}

export {
  isInWXWebview,
  uploadFile,
  decideEnv,
  getUrlParam,
  processParams,
  multiDistrict,
  setWxConfig,
  setWxConfigSync,
  isIOS,
  trim,
  checkImage,
  exportFile,
  watchPrePage
};